﻿using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class DragDrop : MonoBehaviour, IDragHandler, IEndDragHandler, IBeginDragHandler
{
    private int startIndex;
    private int originalIndex;
    private int sibling;

    private float topPadding;
    private float height;
    private float spacing;

    private void OnEnable()
    {
        topPadding = transform.parent.GetComponent<VerticalLayoutGroup>().padding.top;
        spacing = transform.parent.GetComponent<VerticalLayoutGroup>().spacing;
        height = GetComponent<RectTransform>().sizeDelta.y;
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        if (eventData.pointerCurrentRaycast.gameObject.name != "拖动排序") return;
        startIndex = transform.GetSiblingIndex();
        originalIndex = transform.GetSiblingIndex();
        transform.SetSiblingIndex(transform.parent.childCount - 1);
        GetComponent<LayoutElement>().ignoreLayout = true;
    }
    public void OnDrag(PointerEventData eventData)
    {
        if (eventData.pointerCurrentRaycast.gameObject.name != "拖动排序") return;
        transform.position = new Vector3(transform.position.x, eventData.position.y, transform.position.z);
        sibling = -(int)((transform.localPosition.y - topPadding) / (height + spacing));
        transform.parent.GetComponent<DragDropContent>().SetEmpty(sibling);
    }
    public void OnEndDrag(PointerEventData eventData)
    {
        if (eventData.pointerCurrentRaycast.gameObject.name != "拖动排序") return;
        ChangeSibling();
    }

    private void ChangeSibling()
    {
        transform.parent.GetComponent<DragDropContent>().DeActivedEmpty();
        transform.SetSiblingIndex(sibling);
        GetComponent<LayoutElement>().ignoreLayout = false;
    }
}
